<html><head><meta charset="utf-8"><title>使用TypeScript开发Vue组件和使用Vue组件-慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">

<div class="container clearfix" id="top" style="display: block; width: 1134px;">
    
    <div class="center_con js-center_con l" style="width: 1134px;">
        <div class="article-con">
                            <!-- 买过的阅读 -->
                <div class="map">
                    <a href="/read" target="_blank"><i class="imv2-feather-o"></i></a>
                    <a href="/read/35" target="_blank">零基础学透 TypeScript</a>
                    <a href="" target="_blank">
                        <span>
                            / 6-5 使用TypeScript开发Vue组件和使用Vue组件
                        </span>
                    </a>
                </div>

            


            <div class="art-title" style="margin-top: 0px;">
                使用TypeScript开发Vue组件和使用Vue组件
            </div>
            <div class="art-info">
                
                <span>
                    更新时间：2019-08-01 19:57:52
                </span>
            </div>
            <div class="art-top">
                                <img src="https://img2.mukewang.com/5d37f6a20001e0de06400359.jpg" alt="">
                                                <div class="famous-word-box">
                    <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                    <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                    <div class="famous-word">能够生存下来的物种,并不是那些最强壮的,也不是那些最聪明的,而是那些对变化作出快速反应的。<p class="author">——达尔文</p></div>
                </div>
                            </div>
            <div class="art-content js-lookimg">
                <div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">本小节我们将学习使用Vue+TypeScript进行组件的开发和使用。我们在本章前面的小节中，虽然讲了很多内容，但是还没有封装一个可以复用的组件，没有涉及到属性和自定义事件。本小节我们将通过封装一个<strong>CountTo</strong>组件，展示如何封装一个组件。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">首先我们先将创建项目时初始添加的<em>src/views/Home.vue</em>文件改为如下简单结构，把没用的先删掉：</p>
</div><div class="cl-preview-section"><pre class="  language-html"><code class="prism  language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>template</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>home<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>template</span><span class="token punctuation">&gt;</span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">lang</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>ts<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span><span class="token script language-javascript">
<span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> Vue <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'vue-property-decorator'</span>

@<span class="token function">Component</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  name<span class="token punctuation">:</span> <span class="token string">'HomePage'</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">class</span> <span class="token class-name">Home</span> <span class="token keyword">extends</span> <span class="token class-name">Vue</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">&gt;</span></span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">然后我们来封装CountTo组件，这里需要安装一个第三方插件：<code>npm install countup</code>，这个插件可以实现一个数字的动画过渡效果，它虽然有声明文件，但是有问题，所以我们自己写一份声明文件，使用我们自己定义的声明文件。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">首先在根目录下创建一个<em>types</em>文件夹，然后在<em>types</em>文件夹下创建一个<em>countup</em>文件夹，也就是和我们要引入的模块同名的文件夹，然后在这个文件夹下创建一个<em>index.d.ts</em>声明文件。创建好之后，我们要用这个声明文件覆盖<em>node_modules/countup</em>里的声明文件，注意，不是去修改<em>node_modules/countup/index.d.ts</em>文件的内容，而是通过配置<em>tsconfig.json</em>里的<em>paths</em>字段来指定countup模块的声明文件位置，配置如下：</p>
</div><div class="cl-preview-section"><pre class="  language-json"><code class="prism  language-json"><span class="token punctuation">{</span>
  <span class="token string">"comilerOptions"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>
    <span class="token string">"paths"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>
      <span class="token string">"countup"</span><span class="token punctuation">:</span> <span class="token punctuation">[</span>
        <span class="token string">"./types/countup/index.d.ts"</span>
      <span class="token punctuation">]</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这样，当我们使用import去引入countup插件的时候，编译器就会去我们这里指定的路径加载声明文件。接下来我们修改下声明文件，内容如下：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token comment">// types/countup/index.d.ts</span>
<span class="token keyword">declare</span> <span class="token keyword">function</span> <span class="token function">CountUp</span><span class="token punctuation">(</span>target<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">,</span> startVal<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> endVal<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> decimals<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> duration<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> options<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>

<span class="token keyword">declare</span> <span class="token keyword">module</span> CountUp <span class="token punctuation">{</span>
  <span class="token keyword">var</span> options<span class="token punctuation">:</span> CountUpOptions<span class="token punctuation">;</span>
  <span class="token keyword">function</span> <span class="token function">version</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span>
  <span class="token keyword">function</span> <span class="token function">printValue</span><span class="token punctuation">(</span>value<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token keyword">function</span> <span class="token function">count</span><span class="token punctuation">(</span>timestamp<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token keyword">function</span> <span class="token function">start</span><span class="token punctuation">(</span>callback<span class="token punctuation">:</span> <span class="token keyword">Function</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">boolean</span><span class="token punctuation">;</span>
  <span class="token keyword">function</span> <span class="token function">pauseResume</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token keyword">function</span> <span class="token function">reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token keyword">function</span> <span class="token function">update</span><span class="token punctuation">(</span>newEndVal<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">interface</span> <span class="token class-name">CountUp</span> <span class="token punctuation">{</span>
  <span class="token keyword">new</span><span class="token punctuation">(</span>target<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">,</span> startVal<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> endVal<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> decimals<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> duration<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> options<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span><span class="token punctuation">:</span> CountUp<span class="token punctuation">;</span>
  options<span class="token punctuation">:</span> CountUpOptions<span class="token punctuation">;</span>
  <span class="token function">version</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span>
  <span class="token function">printValue</span><span class="token punctuation">(</span>value<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token function">count</span><span class="token punctuation">(</span>timestamp<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token function">start</span><span class="token punctuation">(</span>callback<span class="token operator">?</span><span class="token punctuation">:</span> <span class="token keyword">Function</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">boolean</span><span class="token punctuation">;</span>
  <span class="token function">pauseResume</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token function">reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
  <span class="token function">update</span><span class="token punctuation">(</span>newEndVal<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">interface</span> <span class="token class-name">CountUpOptions</span> <span class="token punctuation">{</span>
  useEasing<span class="token punctuation">:</span> <span class="token keyword">boolean</span><span class="token punctuation">;</span> <span class="token comment">// toggle easing</span>
  useGrouping<span class="token punctuation">:</span> <span class="token keyword">boolean</span><span class="token punctuation">;</span> <span class="token comment">// 1,000,000 vs 1000000</span>
  separator<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span> <span class="token comment">// character to use as a separator</span>
  decimal<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span> <span class="token comment">// character to use as a decimal</span>
  easingFn<span class="token punctuation">:</span> <span class="token keyword">Function</span><span class="token punctuation">;</span> <span class="token comment">// optional custom easing closure function, default is Robert Penner's easeOutExpo</span>
  formattingFn<span class="token punctuation">:</span> <span class="token keyword">Function</span><span class="token punctuation">;</span> <span class="token comment">// optional custom formatting function, default is self.formatNumber below</span>
<span class="token punctuation">}</span>

<span class="token keyword">export</span> <span class="token operator">=</span> CountUp<span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">你可能会奇怪，这些内容怎么写出来的。首先你肯定要去看countup插件的<a href="https://github.com/inorganik/countUp.js">文档</a>，先了解它有哪些api，然后再去看它的根目录下的index.d.ts文件。这里我们修改了一下CountUp接口的定义，添加了options和方法的定义，这样我们在创建实例后，在实例上调用方法就不会报错了。这个声明文件里涉及到的语法知识都比较基础，涉及到基本类型、接口、函数和模块插件声明文件的书写等，如果忘记了这些知识，可以看下前面的小节复习下。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">接下来我们就可以封装CountTo组件了，在<em>src/components</em>文件夹创建<em>CountTo</em>文件夹，然后创建<em>index.tsx</em>文件，在这个文件里，我们先引入需要的装饰器，写下基本的内容：</p>
</div><div class="cl-preview-section"><pre class="  language-tsx"><code class="prism  language-tsx">import { Component, Emit, Prop, Vue, Watch } from 'vue-property-decorator'
import CountUp from 'countup'

@Component({
    name: 'CountTo'
})
export default class CountTo extends Vue {}
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">CountUp是一个构造函数，它有6个参数。第一个是要传入一个html元素的id字符串，用来在这个html标签中显示数值。但我们知道，这个组件肯定是要在多个地方复用的，如果写死一个id，那么在一个页面多次使用这个组件就会有问题，你会发现多个组件只显示了一个。所以这个id就需要是每个组件都独立的，那么就可以利用vue实例上没有提供给外界使用的属性<code>_uid</code>，它是每个组件都唯一的，所以可以利用它拼接一个id。我们来看些如何写：</p>
</div><div class="cl-preview-section"><pre class="  language-tsx"><code class="prism  language-tsx">// ...
export default class CountTo extends Vue {
  public get eleId() { // 计算属性的写法
    return `count_to_${(this as any)._uid}`
  }
}
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这里顺便看一下vue的计算属性在这种类形式组件中的写法，这里只写get读取器函数，如果你学过vue应该知道还可以设置set存值器函数。这里如果直接通过<code>this._uid</code>来获取_uid的值，你会发现会提示<code>类型“CountTo”上不存在属性“_uid”</code>，这是因为vue的声明文件本身是没有提供这个字段的，所以我们可以通过类型断言指定this的类型为any来解决。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">现在id有了，我们就可以来写一下render函数和mounted生命周期钩子了：</p>
</div><div class="cl-preview-section"><pre class="  language-tsx"><code class="prism  language-tsx">// ...
export default class CountTo extends Vue {
    public counter: CountUp = null
    public get eleId() {
        return `count_to_${(this as any)._uid}`
    }
    protected render() {
        return (
            &lt;div class='count-up-wrap'&gt;
                &lt;span id={this.eleId}&gt;&lt;/span&gt;
            &lt;/div&gt;
        )
    }
    protected mounted() {
        this.counter = new CountUp(this.eleId, 0, 1000, 0, 1, {}) // 创建CountUp实例，并保存在counter上
        this.counter.start() // 调用此方法让动画效果开始
    }
}
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">我们看到，这里使用<code>new CountUp</code>来创建实例，第一个参数是html标签id，第二个是起始值，第三个是结束值，第四个是小数点后显示几位，第五个是以秒为单位的动画过渡时长，最后一个是额外的配置项。创建实例后保存在this.counter上，然后调用this.counter的start方法，让动画效果启动。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">现在你可以在home页引入这个组件，看下效果：</p>
</div><div class="cl-preview-section"><pre class="  language-html"><code class="prism  language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>template</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>home<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>count-to</span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>count-to</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>count-to</span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>count-to</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>template</span><span class="token punctuation">&gt;</span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">lang</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>ts<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span><span class="token script language-javascript">
<span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> Vue <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'vue-property-decorator'</span>
<span class="token keyword">import</span> CountTo <span class="token keyword">from</span> <span class="token string">'@/components/CountTo'</span>

@<span class="token function">Component</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  name<span class="token punctuation">:</span> <span class="token string">'HomePage'</span><span class="token punctuation">,</span>
  components<span class="token punctuation">:</span> <span class="token punctuation">{</span>
    CountTo
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">class</span> <span class="token class-name">Home</span> <span class="token keyword">extends</span> <span class="token class-name">Vue</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">&gt;</span></span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">现在你打开Home页，会发现页面上有两个数值，带着动效地从0变为1000，那么说明你封装的组件没问题，如果报错或者没效果，要检查你的代码咯。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">效果有了，现在我们要把里面的一些参数通过组件属性的方式传进去，而不是写死了。我们这里就简单实现两个功能：第一个是传入起始值和结束值，第二个是提供一个update方法供动态设置结束值。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">属性要使用Prop装饰器：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript"><span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">class</span> <span class="token class-name">CountTo</span> <span class="token keyword">extends</span> <span class="token class-name">Vue</span> <span class="token punctuation">{</span>
    @<span class="token function">Prop</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token keyword">type</span><span class="token punctuation">:</span> Number<span class="token punctuation">,</span> <span class="token keyword">default</span><span class="token punctuation">:</span> <span class="token number">0</span> <span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token keyword">public</span> readonly start<span class="token operator">!</span><span class="token punctuation">:</span> <span class="token keyword">number</span>
    @<span class="token function">Prop</span><span class="token punctuation">(</span>Number<span class="token punctuation">)</span> <span class="token keyword">public</span> readonly end<span class="token operator">!</span><span class="token punctuation">:</span> <span class="token keyword">number</span>
    <span class="token comment">// ...</span>
    <span class="token keyword">protected</span> <span class="token function">mounted</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>counter <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CountUp</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>eleId<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>start<span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>end<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">Prop装饰器工厂函数接受的参数和以往开发时给Vue组件属性指定的值一样，可以指定一个类似<em>Number</em>这种类型，也可以是一个数组，也可以是一个对象指定类型和默认值等。然后它修饰的是实例属性，用readonly修饰，因为它是只读的，不可以直接修改，然后我们用<code>!</code>显示赋值断言来指定这个肯定不为null，这样就不会报错了。我们就可以把钩子函数中创建CountUp实例时传的第二、三个参数替换成属性传进来的值了。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">现在我们再使用CountTo组件，就可以指定起始值：</p>
</div><div class="cl-preview-section"><pre class="  language-html"><code class="prism  language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>count-to</span> <span class="token attr-name">:start</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>10<span class="token punctuation">"</span></span> <span class="token attr-name">:end</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>99999<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>count-to</span><span class="token punctuation">&gt;</span></span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">然后我们再在CountTo类里添加一个方法，用于更新数值：</p>
</div><div class="cl-preview-section"><pre class="  language-typescript"><code class="prism  language-typescript">    <span class="token keyword">public</span> <span class="token function">update</span><span class="token punctuation">(</span>endVal<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">)</span><span class="token punctuation">:</span> <span class="token keyword">void</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>counter<span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>endVal<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这样我们在使用CountTo组件的时候如何调用这个方法呢？可以通过ref获取到组件实例，然后调用，我们看下在Home.vue里怎么写：</p>
</div><div class="cl-preview-section"><pre class="  language-html"><code class="prism  language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>template</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>home<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>count-to</span> <span class="token attr-name">ref</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>counter<span class="token punctuation">"</span></span> <span class="token attr-name">:end</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>10000<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>count-to</span><span class="token punctuation">&gt;</span></span>
  <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>template</span><span class="token punctuation">&gt;</span></span>

<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">lang</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>ts<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span><span class="token script language-javascript">
<span class="token keyword">import</span> <span class="token punctuation">{</span> Component<span class="token punctuation">,</span> Vue <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">'vue-property-decorator'</span>
<span class="token keyword">import</span> CountTo <span class="token keyword">from</span> <span class="token string">'@/components/CountTo'</span>

@<span class="token function">Component</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  name<span class="token punctuation">:</span> <span class="token string">'HomePage'</span><span class="token punctuation">,</span>
  components<span class="token punctuation">:</span> <span class="token punctuation">{</span>
    CountTo
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> <span class="token keyword">class</span> <span class="token class-name">Home</span> <span class="token keyword">extends</span> <span class="token class-name">Vue</span> <span class="token punctuation">{</span>
  <span class="token keyword">protected</span> <span class="token function">mounted</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">setInterval</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
      <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>$refs<span class="token punctuation">.</span>counter <span class="token keyword">as</span> CountTo<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">update</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> <span class="token number">10000</span><span class="token punctuation">)</span> <span class="token comment">// 这样每2秒钟这里会更新一次，更新的值是随机的</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token number">2000</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">&gt;</span></span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">其实这里我们完全没必要在CountTo组件里写一个update方法，直接在Home页里通过<code>this.$refs.counter.counter.update()</code>去调用CountTo里保存在counter上的实例方法即可，这里只是为了演示你在使用第三方组件，需要调用它的方法时的方式。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">最后我们学习如何自定义事件。这里我们给CountTo组件添加一个自定义的"on-click"事件，绑定在CountTo组件最外层的html标签上。虽然要在一个组件最外层绑定点击事件，不需要组件提供，直接在组件上使用"@click.native"绑定事件即可，我们这里为了学习使用自定义事件，所以在组件内添加一个事件。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">添加自定义事件可以使用以往<code>this.$emit</code>来抛出事件，也可以使用<em>vue-property-decorator</em>提供的Emit装饰器：</p>
</div><div class="cl-preview-section"><pre class="  language-tsx"><code class="prism  language-tsx">// src/components/CountTo/index.tsx
import { Component, Emit, Prop, Vue, Watch } from 'vue-property-decorator'
import CountUp from 'countup'

@Component({
    name: 'CountTo'
})
export default class CountTo extends Vue {
    // ...

    @Emit('on-click') // 这里的on-click即为自定义事件名
    public click(event) { // 这个方法名用于组件内调用
        return event // return的值即为事件回调函数的参数
    }
    // 这里写完后效果等同于：public click(event) { this.$emit('on-click', event) }

    protected render() {
        return (
            &lt;div class='count-up-wrap' on-click={ this.click }&gt;
                &lt;span id={this.eleId}&gt;&lt;/span&gt;
            &lt;/div&gt;
        )
    }

    // ...
}
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这样我们就可以给CountTo组件绑定on-click事件了：</p>
</div><div class="cl-preview-section"><pre class="  language-html"><code class="prism  language-html"><span class="token comment">&lt;!-- 省略部分代码 --&gt;</span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>count-to</span> <span class="token attr-name">@on-click</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>handleClick<span class="token punctuation">"</span></span> <span class="token attr-name">ref</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>counter<span class="token punctuation">"</span></span> <span class="token attr-name">:end</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>10000<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>count-to</span><span class="token punctuation">&gt;</span></span>
<span class="token comment">&lt;!-- 省略部分代码 --&gt;</span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">lang</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>ts<span class="token punctuation">"</span></span><span class="token punctuation">&gt;</span></span>
// ... 省略部分代码
export default class Home extends Vue {
  public handleClick(event) {
    console.log(event)
  }
  // ...
}
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">CountTo组件到这里就简单封装完了，虽然简单，但是涉及到了很多的知识，你可以再复习下。本章实战部分到这里就结束了，相信你已经学会了如何在Vue中使用TypeScript进行开发了，如果你对Vue还不太了解，可以去查阅下Vue的<a href="https://cn.vuejs.org/">官方文档</a>，还可以参考Vue官方的<a href="https://cn.vuejs.org/v2/guide/typescript.html">TypeScript支持</a>文章。</p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：你可以去 <a href="https://github.com/lison16/imooc-ts-read">Github</a> 获取项目实战源代码！！！</p>
</blockquote>
</div></div>
            </div>
                            <!-- 买过的阅读 -->
                <div class="art-next-prev clearfix">
                                                                        <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/35/article/374">
                                                    <div class="prev l clearfix">
                                <div class="icon l">
                                    <i class="imv2-arrow3_l"></i>
                                </div>
                                <p>
                                    搭建后台界面布局和结合Vuex实现完整登录流程
                                </p>
                            </div>
                        </a>
                                                                                            <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/35/article/376">
                                                    <div class="next r clearfix">
                                <p>
                                    结束语
                                </p>
                                <div class="icon r">
                                    <i class="imv2-arrow3_r"></i>
                                </div>

                            </div>
                        </a>
                                    </div>
                    </div>
        <div class="comments-con js-comments-con" id="coments_con">     <div class="number">精选留言 <span class="js-number">0</span></div>     <div class="comments">         <div class="input-fake js-showcommentModal">             欢迎在这里发表留言，作者筛选后可公开显示         </div>                      <div class="noData">                 <p>                     <i class="imv2-error_c"></i>                 </p>                 <p>目前暂无任何讨论</p>             </div>              </div>  </div>



    </div>
    
    
    

</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>